package com.tanhua.api.mongo;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Double latitude, Double longitude, String address, Long userId) {
        // 1.根据用户id查询
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        // 2、判断
        if (userLocation == null) {
            // 保存
            userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());
            GeoJsonPoint location = new GeoJsonPoint(latitude, longitude); // 创建坐标对象（经纬度）
            userLocation.setLocation(location);
            mongoTemplate.save(userLocation);
        } else {
            // 更新
            Update update = new Update();
            update.set("address", address);
            GeoJsonPoint location = new GeoJsonPoint(latitude, longitude); // 创建坐标对象（经纬度）
            update.set("loation", location);
            update.set("updated", System.currentTimeMillis()); // 本次更新时间
            update.set("lastUpdated", userLocation.getUpdated()); // 上次更新时间

            mongoTemplate.updateFirst(query, update, UserLocation.class);

        }
    }

    @Override
    public List<UserLocationVo> searchNearUser(Long userId, Long meter) {
        // 1、获取当前用户坐标
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);

        // 2、指定半径距
        Distance distance = new Distance(meter / 1000, Metrics.KILOMETERS);// 单位是千米（公里）

        // 参数一：当前用户坐标、参数二：距离
        Circle circle = new Circle(userLocation.getLocation(), distance);// 画圆

        // 3、根据圆做条件搜索附近的人
        Query nearQuery = Query.query(Criteria.where("location").withinSphere(circle));

        List<UserLocation> userLocationList = mongoTemplate.find(nearQuery, UserLocation.class);

        // 4、将UserLocation转成vo，原因是我们通过dubbo传输
        List<UserLocationVo> voList = UserLocationVo.formatToList(userLocationList);

        return voList;
    }
}
